/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.ipo.mm.web.actions;

import java.util.logging.Level;
import java.util.logging.Logger;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.persistence.EntityExistsException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;
import org.apache.struts.util.MessageResources;
import org.ipo.mm.ejb.entities.InstitutionType;
import org.ipo.mm.ejb.entities.User;
import org.ipo.mm.ejb.facade.log.LogFacadeLocal;
import org.ipo.mm.ejb.facade.type.InstitutionTypeFacadeLocal;
import org.ipo.mm.web.formbeans.TypeBean;
import org.ipo.mm.web.util.BreadCrumbs;
import org.ipo.mm.web.util.ConstantManager;
import org.ipo.mm.web.util.UTFEncoder;

/**
 *
 * @author makcro
 */
public class TypeAction extends org.apache.struts.action.Action {

    /**
     * This is the action called from the Struts framework.
     * @param mapping The ActionMapping used to select this instance.
     * @param form The optional ActionForm bean for this request.
     * @param request The HTTP Request we are processing.
     * @param response The HTTP Response we are processing.
     * @throws java.lang.Exception
     * @return
     */
    @Override
    public ActionForward execute(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {

        ActionForward actionForward = null;


        if (isCancelled(request)) {
            actionForward = executeCancel(mapping, form, request, response);
        } else {

            User currentUser = (User) request.getSession().getAttribute(ConstantManager.SESSION_USER_PARAM_NAME);

            TypeBean typeBean = (TypeBean) form;

            MessageResources mResources = getResources(request);
            String saveOperaton = mResources.getMessage(getLocale(request), "gen_create");
            String updateOperation = mResources.getMessage(getLocale(request), "gen_update");

            String submit = typeBean.getSubmit();
            if (saveOperaton.equals(submit)) {
                actionForward = executeCreate(mapping, form, request, response, typeBean, currentUser);
            } else if (updateOperation.equals(submit)) {
                actionForward = executeUpdate(mapping, form, request, response, typeBean, currentUser);
            }

        }

        return actionForward;
    }

    private InstitutionTypeFacadeLocal lookupInstitutionTypeFacade() {
        try {
            Context c = new InitialContext();
            return (InstitutionTypeFacadeLocal) c.lookup("java:comp/env/InstitutionTypeFacade");
        } catch (NamingException ne) {
            Logger.getLogger(getClass().getName()).log(Level.SEVERE, "exception caught", ne);
            throw new RuntimeException(ne);
        }
    }

    private ActionForward executeCreate(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response, TypeBean typeBean, User user) throws Exception {


        ActionForward actionForward;


        InstitutionType newType = new InstitutionType();
        newType.setName(UTFEncoder.encode(typeBean.getName()));
        newType.setNote(UTFEncoder.encode(typeBean.getNote()));
        newType.setUser(user);
        try {

            lookupInstitutionTypeFacade().create(newType);
            // store obj in request so that newly created obj can be automatically selected in list
            request.setAttribute(ConstantManager.REQUEST_TYPE_LAST_CREATED, newType);

            //log
            lookupLogFacade().logCreate(user, ConstantManager.TYPE_NAME, newType.getName());

            notifyOperatoinStatus(ConstantManager.OPERATION_TYPE_CREATE, request);

            BreadCrumbs bc = (BreadCrumbs) request.getSession().getAttribute(ConstantManager.SESSION_BREADCRUMB_PARAM_NAME);
            bc.pop();
            actionForward = bc.pop().getActionForward();

        } catch (EntityExistsException e) {
            ActionMessages errors = new ActionMessages();
            ActionMessage error = new ActionMessage("errors.typeAlreadyExists");

            errors.add("name", error);

            saveErrors(request, errors);
            actionForward = mapping.getInputForward();
        }

        return actionForward;
    }

    private ActionForward executeUpdate(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response, TypeBean typeBean, User user) throws Exception {

        ActionForward actionForward = null;

        InstitutionType type = (InstitutionType) request.getSession().getAttribute("updateType.type");
        try {
            if (type != null) {
                type.setName(UTFEncoder.encode(typeBean.getName()));
                type.setNote(UTFEncoder.encode(typeBean.getNote()));

                lookupInstitutionTypeFacade().edit(type);

                //log
                lookupLogFacade().logUpdate(user, ConstantManager.TYPE_NAME, type.getName());

                notifyOperatoinStatus(ConstantManager.OPERATION_TYPE_UPDATE, request);
                BreadCrumbs bc = (BreadCrumbs) request.getSession().getAttribute(ConstantManager.SESSION_BREADCRUMB_PARAM_NAME);
                bc.pop();
                actionForward = bc.pop().getActionForward();
            } else {
                ActionMessages errors = new ActionMessages();
                ActionMessage error = new ActionMessage("errors.typeAlreadyDeleted");

                errors.add("status", error);

                saveErrors(request, errors);

                BreadCrumbs bc = (BreadCrumbs) request.getSession().getAttribute(ConstantManager.SESSION_BREADCRUMB_PARAM_NAME);
                bc.pop();
                actionForward = bc.pop().getActionForward();
            }


        } catch (EntityExistsException e) {
            ActionMessages errors = new ActionMessages();
            ActionMessage error = new ActionMessage("errors.typeAlreadyDeleted");

            errors.add("name", error);

            saveErrors(request, errors);
            actionForward = mapping.getInputForward();
        }



        return actionForward;
    }

    private ActionForward executeCancel(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response) throws Exception {


        BreadCrumbs bc = (BreadCrumbs) request.getSession().getAttribute(ConstantManager.SESSION_BREADCRUMB_PARAM_NAME);
        bc.pop();
        ActionForward actionForward = bc.pop().getActionForward();
        return actionForward;
    }

    private LogFacadeLocal lookupLogFacade() {
        try {
            Context c = new InitialContext();
            return (LogFacadeLocal) c.lookup("java:comp/env/LogFacade");
        } catch (NamingException ne) {
            Logger.getLogger(getClass().getName()).log(Level.SEVERE, "exception caught", ne);
            throw new RuntimeException(ne);
        }
    }

    private void notifyOperatoinStatus(String operationMessageKey, HttpServletRequest request) {

        MessageResources mResources = getResources(request);
        String typeEntityName = mResources.getMessage(getLocale(request), ConstantManager.TYPE_ENTITY_NAME_RES_KEY);

        ActionMessages messages = new ActionMessages();
        ActionMessage actionMessage = new ActionMessage(operationMessageKey, typeEntityName);
        messages.add("operation_status", actionMessage);
        saveMessages(request, messages);
        
    }
    
}
